package www.woniuxy.com.class112.util;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import lombok.Data;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
@Data
@ConfigurationProperties(prefix = "huyi")
public class SMSUtil {
    private String url;
    private String account;
    private String password;
    //调用hutool工具向互亿无线短信平台发送HTTP请求
    //向手机发送验证码
    public String sendCode(String mobile)throws Exception{
        Map<String,Object> param = new HashMap<>();
        param.put("account",account);
        param.put("password",password);
        param.put("mobile",mobile);
        long code=(long)(Math.floor(Math.random()*9000)+1000);
        System.out.println(code);
        String content="您的验证码是："+code+"。请不要把验证码泄露给其他人。";
        param.put("content",content);
        HttpResponse response = HttpRequest.post(url).form(param).timeout(20000).execute();
        Document doc = DocumentHelper.parseText(response.body());
        Element root = doc.getRootElement();
        String result = root.elementText("code");
        System.out.println(result);
        if("2".equals(result)){
            return code+"";
        }else{
            throw new Exception("短信发送失败");
        }
    }
}
